var newtasks; // 保存新任务信息的变量

var taskFId = null; // 任务父ID
var eventId = null; //事件ID

function setTaskFId(tid) {
	taskFId = tid;
}

$(document).ready(function() {

	function getCurrentTime() {
		var now = new Date();
		var year = now.getYear();
		var month = now.getMonth() + 1;
		var day = now.getDate();
		var hour = now.getHours();
		var minute = now.getMinutes();
		var second = now.getSeconds();
		return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":"
				+ second;
	}

	$("#taskTime").attr("value", getCurrentTime());
	$("#taskTime").attr("disabled", true);

	// 任务附件的信息载体
	function annexMsg() {
		this.tid = "";
		this.filename = "";
		this.fileid = "";
	}

	var annexArray = new Array(); // 保存任务附件的数组

	// 上传窗口的
	$("#uploadFrame").dialog({
		autoOpen : false,
		width : 460,
		modal : true,
		resizable : false,
		close : function() {
			$("#upListDIV").empty();

			var myFileArr = window.frames["uploadFrame"].getFileArray();
			$.each(myFileArr, function(i, n) {
				var htmlStr = "";
				htmlStr += "<div><img src='lzm/images/doc.gif'/><span class='fn'>"
				htmlStr += n.originName;
				htmlStr += "</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
				htmlStr += "<span class='crtName' style='display:none;'>";
				htmlStr += n.crtName;
				htmlStr += "</span><span class='dell'>删除</span></div>";
				$('#upListDIV').append(htmlStr);
			});
			$('.dell').unbind("click");
			$('.dell').click(function() {
						$(this).parent().remove();
					});
			$("#upListDIV").show();

		}
	});

	// “上传附件”按钮的响应
	$("#upFile").click(function() {
				$("#uploadFrame").dialog("open");
			});

	// ‘添加任务’按钮的动作设置
	$('#addTask').click(function() {

		var dept = $("#deptRestult").text();

		$("#taskDept").val(dept);
		var t_name = $("#taskName").val();
		var t_context = $("#taskContext").val();
		var t_leader = $("#taskLeader").val();
		var t_people = $("#taskPeople").val();
		var t_time = $("#taskTime").val();
		var t_res = $("#taskRes").val();

		if (t_name != "" && t_context != "" && t_leader != "" && t_people != ""
				&& t_time != "" && t_res != "") {

			// alert($("#upListDIV").children.length);
			// 上传附件功能的验证
			if (($("#upListDIV").children.length == 1)) {
				alert("请上传已选则的附件！");
				return false;
			}
			// alert("add task ");
			$.ajax({
						type : "post",
						url : "lzw/addTask_getNewTaskNo.action",
						data : "num=" + $("#selDepts").get(0).options.length, // 获取要新增的任务数
						dataType : "JSON",
						success : addTaskHtml,
						error : function(textStatus) {
							alert("Ajax请求失败，请检查本地的网络连接！");
							return false;
						}
					});

		} else {
			alert("请填写完整的任务信息！");
		}

		return false;
	});

	function addTaskHtml(data) {

		var d = eval("(" + data + ")");

		if (d.newTaskIds == null && data.errMsg != null) {
			alert(data.errMsg);
			return false;
		}
		var t_name = $("#taskName").val();
		var t_context = $("#taskContext").val();
		// var t_dept = $("#taskDept").val();
		// alert("部门："+t_dept);
		var t_time = $("#taskTime").val();

		var sel_Depts = new Array();
		var sel_Users = new Array();
		var sel_Names = new Array();
		$("#selDepts option").each(function(i) {
					sel_Names[i] = $(this).text();
					sel_Depts[i] = $(this).attr("value");
					sel_Users[i] = $(this).attr("name");
				});

		$.each(d.newTaskIds, function(i, n) {

			// 新添加的任务信息表
			var strhtml1 = "<tr class='newtasktr'>";
			// 任务表的任务号列
			strhtml1 += "<td height='18' class='tdbgcolor'><div align='center'>"
					+ n + "</div></td>";
			// 任务名称列
			strhtml1 += "<td height='18' class='tdbgcolor'><div align='center'>"
					+ t_name + "</div></td>";
			// 任务类容列
			strhtml1 += "<td height='18' class='tdbgcolor'><div align='center'>"
					+ $.trim(t_context) + "</div></td>";
			// 负责任务的部门列
			strhtml1 += "<td height='18' class='tdbgcolor'><div align='center' "
					+ "name="
					+ sel_Users[i]
					+ " "
					+ "value="
					+ sel_Depts[i]
					+ ">" + sel_Names[i] + "</div></td>"
			// 任务分派时间列
			strhtml1 += "<td height='18' class='tdbgcolor'><div align='center'>"
					+ t_time + "</div></td>";
			// 任务编辑列
			strhtml1 += "<td height='18' class='tdbgcolor'><div align='center'><input type='button' value='删除' "
					+ "onclick='this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode);return false'/>"
					+ "</div></td></tr>";

			// $("#newTask").clone().show().appendTo($('#newTable'));
			$("#newTable").append(strhtml1);

			var taskid = n;
			$("#upListDIV > *").each(function(i, n) {
						var oneAnnexMag = new annexMsg();
						oneAnnexMag.filename = $(this).find(".fn").text();
						oneAnnexMag.fileid = $(this).find(".crtName").text();
						oneAnnexMag.id = taskid;
						annexArray.push(oneAnnexMag);
					});

		});

		$("#upListDIV").empty();
		$("#taskName").val("");
		$("#taskContext").val("");
		$("#taskDept").val("");
		//czy start 
		$("#taskTime").attr("value", getCurrentTime());
//		$("#taskTime").val("");
		//czy end
		
		$("#fileField").text("");
		$("#deptRestult").text("");
		// $("#deptRestult").text("");

		// 跟随鼠标改变背景色的函数
		changetTrColor(".newtasktr");
		// $('#upFile').attr({disabled:"false"});
		// $("#fileField").attr('value',"");
	}

	function getAllTaskAsParam() {
		var param;
		var T_id;
		var T_name;
		var T_context;
		var T_deptId;
		var T_time;
		var T_uid;
		// var T_filename = new Array();
		// var T_fileid = new Array();
		var arr = new Array();
		$("#newTable").find("tr").each(function(i, m) {
			if (i > 0) { // 跳过新任务表的第一行
				var T_filename = new Array();
				var T_fileid = new Array();
				$(this).find("td").each(function(j, n) {
							switch (j) {
								case 0 :
									var ids = $(this).text();
									T_id = ids;
									var cookie = $.cookie('newtaskids'); // 创建一个cookie用来保存新建任务的ID
									if (cookie != null) {
										cookie = cookie + "+" + ids;
										$.cookie('newtaskids', cookie);
									} else {
										$.cookie('newtaskids', ids);
									}

									$.each(annexArray, function(i, n) {
												if (T_id == n.id) {
													T_filename.push(n.filename);
													T_fileid.push(n.fileid);
												}
											});

									break
								case 1 :
									T_name = $(this).text();
									break
								case 2 :
									T_context = $(this).text();
									break
								case 3 :
									// var deptName = $(this).text();

									T_uid = $(this).children("div")
											.attr("name");
									T_deptId = $(this).children("div")
											.attr("value");
									/*
									 * $("#selDepts option").each(function() { //
									 * 遍历所选的部门，根据所选的部门名称获得其ID
									 * 
									 * if ($(this).text() == deptName) {
									 * T_deptId = $(this).val();
									 *  }
									 * 
									 * });
									 */
									break
								case 4 :
									T_time = $(this).text();
									break
								default :
									break
							}
						});
				// 用变量拼成一次遍历的字符串，并用数组保存
				param = "{\"id\":\"" + T_id + "\",\"name\":\"" + T_name
						+ "\",\"context\":\"" + T_context
						+ "\",\"filename\":\"" + T_filename.toString()
						+ "\",\"fileid\":\"" + T_fileid.toString()
						+ "\",\"deptID\":\"" + T_deptId + "\",\"uid\":\""
						+ T_uid + "\",\"time\":\"" + T_time + "\"}";
				arr[i] = param;
			}
		});
		var params = "{\"TaskInfo\":[";
		$.each(arr, function(i) {
					if (i > 0) {
						params = params + arr[i] + ",";
					}
				});
		params = params + "]}";

		return params;
	}

	function addTaskSucc(data) {
		// alert(data);
		var d = eval("(" + data + ")");
		if (d.errMsg == null) {
			window.location.href = "/ag/zhh/zhhaddtask_succ3.jsp";
		} else {
			alert(d.errMsg);
			$.cookie('newtaskids', null); // 使COOKIE失效
			return false;
		}

	}

	// 提交任务分配的结果，并跳转页面
	$("#newTaskFinish").click(function() {

				// 获取table的行数：document.getElementById('newTable').getElementsByTagName('tr').length;
				// alert($("#newTable").find("tr").length);
				var tr = $("#newTable").find("tr").length;
				if (tr > 1) {
					//var p = $.cookie('taskEventId');
					//var pp = $.trim(p);

					// var pFTID = $.cookie('tasktrackid');
					//var ppFTID = taskFId;

					var temp = getAllTaskAsParam();
					// alert(temp);
					// 把拼成的字符串转成json对象
					var d = eval("(" + temp + ")");
					// 将JSON对象转换成字符串
					var strParam = JSON.stringify(d);
					// alert(strParam);
					$.ajax({
								type : "post",
								url : "lzw/addTask_saveNewTask.action",
								data : {
									"newTaskJson" : strParam,
									"taskEventID" : eventId,
									"taskFatherID" : taskFId
								},
								dataType : "JSON",
								success : addTaskSucc,
								error : function(textStatus) {
									alert("Ajax请求失败，请检查本地的网络连接！");
									$.cookie('newtaskids', null);
									return false;
								}
							});
				} else {
					alert("请添加新任务!");
					return false;
				}

			});

});
